package com.sentrix.auto.printercenter.infrastructure.agentserver;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sentrix.auto.printercenter.application.AgentService;
import com.sentrix.auto.printercenter.common.AssertUtil;
import com.sentrix.auto.printercenter.infrastructure.util.SpringContextHolder;
import com.sentrix.auto.printercenter.infrastructure.agentserver.dto.BaseWebSocketResMsg;
import com.sentrix.auto.printercenter.infrastructure.agentserver.dto.Uid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
public class AgentClientManager {
    // 存储所有连接的Session及其对应的锁（线程安全的Map）
    private static final Map<WebSocketSession, Lock> SESSION_LOCKS = new ConcurrentHashMap<>();
    private final ObjectMapper objectMapper = new ObjectMapper();
    private static final Map<String, WebSocketSession> PRINT_CLIENTS = new ConcurrentHashMap<>();
    private volatile AgentService agentService;

    private static final class InstanceHolder {
        private static final AgentClientManager instance = new AgentClientManager();
    }

    public static AgentClientManager instance() {
        return InstanceHolder.instance;
    }

    public void addClient(String macAddress, WebSocketSession session) {
        if (Objects.isNull(agentService)) {
            synchronized (AgentClientManager.class) {
                if (Objects.isNull(agentService)) {
                    agentService = SpringContextHolder.getBean(AgentService.class);
                }
            }
        }

        synchronized (AgentClientManager.class) {
            //移除旧的session
            WebSocketSession oldSession = PRINT_CLIENTS.remove(macAddress);
            if (Objects.nonNull(oldSession) && oldSession.isOpen()) {
                try {
                    oldSession.close();
                } catch (Exception e) {
                    log.error("关闭session异常", e);
                }
            }
            PRINT_CLIENTS.put(macAddress, session);
            SESSION_LOCKS.put(session, new ReentrantLock());
            agentService.handleConnect(macAddress, session.getId());
        }
    }

    public synchronized void removeClient(WebSocketSession session) {
        SESSION_LOCKS.remove(session);
        if (PRINT_CLIENTS.isEmpty()) {
            return;
        }
        List<String> waitingRemoveMac = new ArrayList<>();
        for (Map.Entry<String, WebSocketSession> entry : PRINT_CLIENTS.entrySet()) {
            if (Objects.nonNull(entry.getValue())) {
                if (session.getId().equals(entry.getValue().getId())) {
                    waitingRemoveMac.add(entry.getKey());
                }
            }
        }

        waitingRemoveMac.forEach(mac -> {
            WebSocketSession removingSession = PRINT_CLIENTS.remove(mac);
            log.info("session 退出，session状态：{}", removingSession.isOpen());
            if (removingSession.isOpen()) {
                try {
                    removingSession.close();
                } catch (Exception e) {
                    log.error("关闭session异常:{}", e.getMessage());
                }
            }
            agentService.handleDisconnect(mac);
        });

    }

    /**
     * 检查客户端是否在线
     */
    public boolean isClientOnline(String mac) {
        WebSocketSession session = PRINT_CLIENTS.get(mac);
        return session != null && session.isOpen();
    }

    /**
     * 封转消息的同步发送和相应
     *
     * @param mac
     * @param message
     * @param messageWaitTimeout
     * @param <T>
     * @return
     */
    public <T extends Uid> BaseWebSocketResMsg sendMessage(String mac, T message, int messageWaitTimeout) {
        WebSocketSession client = PRINT_CLIENTS.get(mac);
        if (Objects.isNull(client)) {
            log.error("agent 还未连接server:{}", mac);
            throw new RuntimeException("agent is null");
        }
        if (!client.isOpen()) {
            SESSION_LOCKS.remove(client);
            throw new RuntimeException("agent is offline");
        }
        // 获取该Session对应的锁
        Lock lock = SESSION_LOCKS.get(client);
        AssertUtil.assertNotNull(lock, "lock is null");
        try {
            lock.lock();
            client.sendMessage(new TextMessage(objectMapper.writeValueAsString(message)));
        } catch (IOException e) {
            log.error("发送消息异常:{}", e.getMessage());
            throw new RuntimeException(e.getMessage());
        } finally {
            lock.unlock();
        }
        return WebSocketResSyncHandler.instance().waitForResponse(message.getUid(), messageWaitTimeout);
    }
}
